#!/usr/bin/env python
import os 
import sys 
import scipy.sparse as scp 
import numpy as nmp

class Helper :

	# reads ABC format file and returns map of {(key,idx)} and lists I,J,V
	# containing row,col,val resp.
	@staticmethod 
	def parse_abc_file(filename, basedir) :
		map_keys = {}

		I, J, V = [], [], [] 
		f = open (os.path.join(basedir, filename)) 
		f = f.readlines()

		for line in f :
			values = line.split(' ') 
			if map_keys.get(values[0]) == None:
				map_keys[values[0]] = len(map_keys)
			if map_keys.get(values[1]) == None:
				map_keys[values[1]] = len(map_keys)

		for line in f :
			values = line.split(' ')
			#row_idx = map_keys.get(values[0]) col_idx =
			#map_keys.get(values[1]) matrix[row_idx][col_idx] =
			#float(str.strip(values[2]))
			I.append(map_keys.get(values[0])) 
			J.append(map_keys.get(values[1])) 
			V.append(float(str.strip(values[2])))

		I, J = nmp.array(I, nmp.int32), nmp.array(J, nmp.int32) 
		V = nmp.array(V, nmp.float)

		return I, J, V, map_keys

	@staticmethod 
	def build_COO_matrix(I, J, V, n) :
		return scp.coo_matrix((V, (I, J)), shape=(n, n)).tocsr()

	@staticmethod 
	def parse_build_dcsc(filename, basedir) :
		AUX, JC, CP, IR, NUM = [], [], [], [], [] 
		_j = -1
		f = open (os.path.join(basedir, filename)) 
		f = f.readlines()
		
		for n, line in enumerate(f):
			values = line.split(' ') 
			i, j, v = int(values[0].strip()), int(values[1].strip()), float(values[2].strip()) 
			if _j != j :
				JC.append(j-1)
				CP.append(n)
			IR.append(i-1) 
			_j = j
			NUM.append(v)
		return AUX, JC, CP, IR, NUM

	@staticmethod 
	def parse_build_dcsr(filename, basedir) :
		AUX, IR, RP, JC, NUM = [], [], [], [], [] 
		_i = -1
		f = open (os.path.join(basedir, filename)) 
		f = f.readlines()
		
		for n, line in enumerate(f):
			values = line.split(' ') 
			i, j, v = int(values[0].strip()), int(values[1].strip()), float(values[2].strip()) 
			if _i != i :
				JC.append(j-1)
				RP.append(n)
			IR.append(i-1)
			_i = i
			NUM.append(v)
		return AUX, IR, RP, JC, NUM


